package top.tervest.easyshare.common.security.auth;


import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.context.SecurityContextPersistenceFilter;
import org.springframework.stereotype.Component;
import top.tervest.easyshare.common.exception.PasswordErrorException;
import top.tervest.easyshare.common.exception.UserNotFoundException;

import java.util.Collection;
import java.util.Objects;;

/**
 * @author ZhangNanNan
 * @create 2019-01-16 14:09
 */
@Component
public class AuthenticationProviderImpl implements AuthenticationProvider {

    @Autowired
    private UserDetailsServiceImpl udsi;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String name = authentication.getName();
        String pwd = (String) authentication.getCredentials();
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl)udsi.loadUserByUsername(name);
        if (Objects.isNull(userDetails)) {
            throw new UserNotFoundException("没有该用户");
        }
        String password = userDetails.getPassword();
        if (!pwd.equals(password)) {
            throw new PasswordErrorException("密码错误");
        }
        Collection<? extends GrantedAuthority> authorities = userDetails.getAuthorities();
        return new UsernamePasswordAuthenticationToken(userDetails,password,authorities);

    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }

}
